package com.face.service;

import com.face.common.Page;
import com.face.dao.RemarkDao;
import com.face.dao.UserDao;
import com.face.dao.VisitDao;
import com.face.entity.Remark;
import com.face.exception.DatabaseException;
import com.face.util.DateUtil;
import com.face.wrapper.RemarkWrapper;
import com.face.wrapper.UserWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.*;

@Service
public class RemarkService {

    @Autowired
    private RemarkDao remarkDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserService userService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private VisitDao visitDao;

    public int saveRemark(Remark remark) {
        Date date = new Date();
        remark.setCreateTime(new Timestamp(date.getTime()));
        remark.setUpdateTime(new Timestamp(date.getTime()));
        int id = remarkDao.saveRemark(remark);
        if (id < 0) {
            throw new DatabaseException("order", "save", "order");
        }
        return id;
    }

    public List<Remark> getRemarksByUserId(String userId, Integer limit) {
        List<Remark> list = new ArrayList<Remark>();
        if (limit == null) {
            list = remarkDao.getRemarksByUserId(userId);
        } else {
            list = remarkDao.getRecentRemarks(userId, limit);
        }

        return list;
    }

    public List<Remark> getRemarks(String userId, String start, String end) {
        return remarkDao.getRemarks(userId, start, end);
    }

    public Page<RemarkWrapper> list(String shopId, Integer page, Integer limit, String start, String end, String sort, String order) {
        String orderClause = "";
        if (sort == null || sort.isEmpty()) {
            orderClause += "updateTime";
        }
        if (order == null || order.isEmpty()) {
            orderClause += " ";
            orderClause += "desc";
        }

        if (start == null || start.isEmpty() || end == null || end.isEmpty()) {
            return remarkDao.listAll(shopId, page, limit, orderClause);

        }
        return remarkDao.list(shopId, page, limit, start, end, orderClause);
    }

    public Integer count(String shopId, String start, String end) {
        return remarkDao.count(shopId, start, end);
    }

    public Integer count(String shopId) {
        return remarkDao.count(shopId);
    }

    public Page<RemarkWrapper> getNewestRemarkList(String shopId, Integer page, Integer limit, String start, String end) {
        if (start == null || start.isEmpty() || end == null || end.isEmpty()) {
            return remarkDao.getNewestRemarkList(shopId, page, limit);
        }
        return remarkDao.getNewestRemarkList(shopId, page, limit, start, end);
    }

    public Page<Map<String, Object>> getRemarkCountList(String shopId, Integer page, Integer limit, String start, String end) {
        if (start == null || start.isEmpty() || end == null || end.isEmpty()) {
            return remarkDao.getRemarkCountList(shopId, page, limit);
        }
        return remarkDao.getRemarkCountList(shopId, page, limit, start, end);
    }

    public Page<RemarkWrapper> listAllByUserId(String shopId, String userId, Integer page, Integer limit, String start, String end) {
        return remarkDao.listAllByUserId(shopId, userId, page, limit, start, end);
    }

    public Map<String, Object> getChartData(String shopId, String start, String end, Integer type) {
        List<Map<String, Object>> newCount = new ArrayList<>();        //新用户数
        List<Map<String, Object>> oldCount = new ArrayList<>();         //老客户到访次数，没有登记的也算
        List<String> dates = new ArrayList<>();                        //日期列表

        if (type == 1) { //按天
            oldCount = visitDao.statByDay(shopId, start, end);
            newCount = userDao.dailyCount(shopId, start, end);
            dates = DateUtil.getDays(start, end);
        } else if (type == 2) {    //按月
            newCount = userDao.monthlyCount(shopId, start, end);
            oldCount = visitDao.statByMonth(shopId, start, end);
            dates = DateUtil.getMonths(start, end);
        }
        Map<String, Object> result = new HashMap<>();
        long[] newUserCountList = new long[dates.size()];
        long[] oldUserCountList = new long[dates.size()];
        int index1 = 0;
        int index2 = 0;
        for (int i = 0; i < dates.size();i++) {
            if (index1 < oldCount.size() && oldCount.get(index1).get("date").equals(dates.get(i))) {
                oldUserCountList[i] = (long) oldCount.get(index1).get("count");
                index1++;
            } else {
                oldUserCountList[i] = 0;
            }

            if (index2 < newCount.size() && newCount.get(index2).get("date").equals(dates.get(i))) {
                newUserCountList[i] = (long) newCount.get(index2).get("count");
                index2++;
            } else {
                newUserCountList[i] = 0;
            }
        }
        result.put("newCustomer", newUserCountList);
        result.put("oldCustomer", oldUserCountList);
        result.put("dates", dates);
        return result;
    }

    public Map<String, Object> getRemarkCountData(String shopId, String start, String end, Integer type) {
        List<Map<String, Object>> allCount = new ArrayList<>();        //所有记录数
        List<String> dates = new ArrayList<>();                        //日期列表
        if (type == 1) { //按天
            allCount = remarkDao.dailyRemarkCount(shopId, start, end);
            dates = DateUtil.getDays(start, end);
        } else if (type == 2) {    //按月
            allCount = remarkDao.monthlyRemarkCount(shopId, start, end);
            dates = DateUtil.getMonths(start, end);
        }
        Map<String, Object> result = new HashMap<>();
        long[] remarkCountList = new long[dates.size()];

        for (int i = 0; i < allCount.size(); i++) {
            String date = (String) allCount.get(i).get("date");
            int index = dates.indexOf(date);
            remarkCountList[index] = (long) allCount.get(i).get("count");
        }
        result.put("remarkCount", remarkCountList);
        result.put("dates", dates);
        return result;
    }

    public Integer todayCount(String shopId) {
        List<Map<String, Object>> list = remarkDao.dailyCount(shopId, new Date().toString(), new Date().toString());
        if (list.size() == 0) {
            return 0;
        }
        return (Integer) list.get(0).values().toArray()[0];
    }

    public List<RemarkWrapper> getRecentRemarksByShopId(String shopId, int limit) {
        return remarkDao.getRecentRemarksByShopId(shopId, limit);
    }

    public List<Map<String, String>> getRemarksForWx(String openid, String userId, String start, String end, String keyword) {

        userService.determineAuthority(openid, userId);

        List<Map<String, String>> list = remarkDao.getRemarksForWx(userId, start, end, keyword);
        return list;
    }

    public Integer addRemarkByOpenid(Remark remark, String openid) {

        UserWrapper userWrapper = userService.determineAuthority(openid, remark.getUserId());
        Integer visitCount = userWrapper.getVisitCount();
        userWrapper.setVisitCount(null != visitCount && visitCount > 0 ? visitCount + 1 : 2);
        userWrapper.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        userDao.updateUser(userWrapper);

        remark.setRemarkId(null);
        remark.setCreator(accountService.findUsernameByOpenid(openid));
        return saveRemark(remark);
    }
}
